<?php
/**
 * Created by PhpStorm.
 * User: chenguangpeng
 * Date: 15-6-9
 * Time: 下午8:15
 * 演出类
 */

namespace PFT\Show;


class PftShow {
    private $db;

    public function __construct(\PDO $db=null)
    {
        $this->db = $db;
    }

    /**
     * 检测时间是否存在交集
     *
     * @param string $bt1 开始时间1
     * @param string $et1 结束时间1
     * @param string $bt2 开始时间2
     * @param string $et2 结束时间2
     * @return bool
     */
    public function isMixDate($bt1, $et1, $bt2, $et2)
    {
        return $bt1 <= $et2 && $et1 >= $bt2;
    }

    /**
     *
     *
     * @param int $lid
     * @param string $begin_date
     * @param string $end_date
     * @param array $weeks_arr
     * @return bool
     */
    public function CheckDate($lid, $begin_date, $end_date, $weeks_arr)
    {
        $sql_chk = "SELECT id,begin_date,end_date,weeks FROM `pft_roundplan` WHERE lid=?";
        $stmt = $this->db->prepare($sql_chk);
        $stmt->execute(array($lid));
        $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        if (!$result) return true;
        foreach($result as $row) {
            if ($this->isMixDate($row['begin_date'], $row['end_date'],
                    $begin_date, $end_date)===true)
            {
                $weeks_arr_chk = explode('|', $row['weeks']);
                $chk_2         = array_intersect($weeks_arr, $weeks_arr_chk);
                if (count($chk_2)) {
                    return array(
                        $row['begin_date'],
                        $row['end_date'],
                        $chk_2
                    );
                }
            }
        }

    }

    /**
     * 检测场馆是否存在
     *
     * @param int $venus_id 场馆ID
     * @return string
     */
    public function CheckVenusExist($venus_id)
    {
        $sql = "SELECT id FROM pft_venues WHERE id={$venus_id} LIMIT 1";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        return $stmt->fetchColumn(0);
    }
    /**
     * 创建场次计划
     * @return array
     */
    public function CreateRoundPlan()
    {
        $lid        = $_POST['lid'];
        $begin_date = $_POST['begin_date'];
        $end_date   = $_POST['end_date'];
        $autopub    = $_POST['autopub'] > 0 ? 1 : 0;//是否自动发布
        //检测场馆是否存在
        if (!$this->CheckVenusExist($_POST['venus_id'])) {
            return array('status'=>'fail', 'msg'=>'场馆不存在');
        }
        if (strlen($_POST['weeks'])>14 ) {
            return array(
                'status'=>'fail',
                'msg'   =>'适用日期格式错误',
            );
        }

        $weeks_arr = array_filter(explode('|', $_POST['weeks']), function($val){
            return is_numeric($val) && $val<7;
        });
        $week_txt = array('周天','周一','周二','周三','周四','周五','周六');
        //自动发布计划 的适用日期及适用星期 不能冲突
        if ($autopub==1) {
            $chkRet = $this->CheckDate($lid, $begin_date, $end_date, $weeks_arr);
            if ($chkRet!==true) {
                $week_exist = array_map( function($val) use ($week_txt){
                    return $week_txt[$val];
                },$chkRet[2]);
                $week_msg   = implode(',',$week_exist);
                unset($week_exist);
                return array(
                    'status'=>'fail',
                    'msg'=>"日期存在冲突,{$chkRet[0]}至{$chkRet[1]}内，{$week_msg}已存在",
                );
            }
        }

        $round_list = json_encode($_POST['round_list']);
        $weeks      = count($weeks_arr) ? implode('|', $weeks_arr) : '0|1|2|3|4|5|6';
        $status     = intval($_POST['status']);//状态
        $sql_ins = <<<SQL
INSERT INTO pft_roundplan(lid,round_list,begin_date,end_date,weeks,
autopub,status,opid,create_time) VALUES(?,?,?,?,?,?,?,?,now())
SQL;
        try {
            $stmt = $this->db->prepare($sql_ins);
            $stmt->execute(
                array(
                    $lid,
                    $round_list,
                    $begin_date,
                    $end_date,
                    $weeks,
                    $autopub,
                    $status,
                    $_SESSION['memberID']
                )
            );
            return array('status'=>'success', 'msg'=>'ok');
        } catch (\PDOException $e) {
            return array('status'=>'fail', 'msg'=>$e->getMessage());
        }
    }

    public function SyncRound($venus_id, $sync_date, $use_dates)
    {
        $sql = "SELECT round_name,bt,et,pre_sale FROM pft_round WHERE venus_id=? AND use_date=? AND status=0";
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($venus_id, $sync_date));
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
       foreach($rows as $row) {
            foreach($use_dates as $date) {
                $ret = $this->CreateRound(0, $venus_id, $row['round_name'], $row['bt'], $row['et'], $date, $row['pre_sale'],$_SESSION['sid'] );
                if ($ret['status']!='ok')  {
                    return $ret;
                }
            }
        }
        return array('status'=>'ok', 'msg'=>'ok');

    }

    public function SetRoundState($rid, $state)
    {
        //取消场次
        if ($state==1) {
            $sql = "SELECT ordernum,opid FROM pft_roundseat_dyn WHERE round_id=$rid AND status=3";
            include '../../class/SoapInit.class.php';
            $soap = \SoapInit::GetSoapInside();
            $stmt = $this->db->prepare($sql);
            $stmt->execute();
            $log     = '';
            $ok_list = array();
            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                if ($row['opid']!=$_SESSION['memberID']) {
                    return false;
                };
                $res = $soap->Order_Change_Pro($row['ordernum'], 0, -1, 0, $_SESSION['memberID']);
                if ($res==1) {
                    $ok_list[] = $row['ordernum'];
                }
                $log .= "因场次删除取消订单[{$row['ordernum']}]返回{$res};\n";
            }
            if ($cnt = count($ok_list)) {
                $sql_update = "UPDATE pft_roundseat_dyn SET state=4 WHERE ordernum IN("
                    .implode(',', $ok_list).") LIMIT $cnt";
                $this->db->exec($sql_update);
            }
            write_logs($log, '/var/www/html/new/d/logs/pft_show/order_cancel.txt');
        }
        $sql = "UPDATE pft_round SET status=? WHERE id=? LIMIT 1";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute(array($state, $rid));
    }

    /**
     * 创建场次
     *
     * @param int $lid 景区ID
     * @param int $venus_id 分区ID
     * @param string $name 场次名称
     * @param string $bt 开始时间 00:00
     * @param string $et 结束时间 23:59
     * @param string $day 适用日期
     * @param int $opid 操作人ID
     * @param int $pre_sale 预售天数
     * @param int $status 状态
     * @param int $rid 场次ID
     * @return array
     */
    public function CreateRound($lid,$venus_id, $name, $bt, $et, $day,$pre_sale,
                                $opid, $status=0, $rid=0)
    {
        //检测场馆是否存在
        if (!$this->CheckVenusExist($venus_id)) {
            return array('status'=>'fail', 'msg'=>'场馆不存在');
        }
        //日期冲突检查
        $sql_chk    = "SELECT id,bt,et,round_name FROM pft_round WHERE venus_id=? AND use_date=? AND status=0"
            . ($rid>0 ? " AND id<>$rid" : "");
        $stmt = $this->db->prepare($sql_chk);
        $stmt->execute(array($venus_id, $day));
        $name_list = array();
        while ($list = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            if (isset($name_list[$list['round_name']])) {
                return array(
                    'status'=>'fail',
                    'msg'=> "同一个天内场次名称不能重复，【{$day}-{$name}】名称已存在",
                );
            } else {
                $name_list[$list['round_name']] = $list['id'];
            }
            if ($this->isMixDate($list['bt'], $list['et'], $bt, $et)===true)
            {
                return array(
                    'status'=>'fail',
//                    'msg'=> "【{$day}】时间存在冲突:{$list['bt']}-{$list['et']};$bt - $et",
                    'msg'=> "[{$day} {$list['bt']}至{$list['et']}]存在在场次{$list['round_name']};{$name}-{$bt}至{$et}保存失败",
                );
            }
        }
        unset($name_list);
        if ($rid>0) {
            $sql = <<<SQL
            UPDATE pft_round SET round_name=?,bt=?,et=?,
            pre_sale=?,status=? WHERE id=? LIMIT 1
SQL;
            $arr = array($name,$bt, $et,$pre_sale,$status, $rid);
        }
        else {
            $sql = <<<SQL
        INSERT INTO pft_round(lid,venus_id,round_name,bt,et,use_date,pre_sale,status,
        opid,publish_time)
        VALUES(?,?,?,?,?,?,?,?,?,now())
SQL;
            $arr = array($lid, $venus_id, $name,$bt, $et, $day, $pre_sale, $status, $opid);
        }
        //添加——tag
        $sql_tag = "INSERT INTO pft_round_tag (tag) VALUES('{$venus_id}_{$bt}_{$name}')";
        $this->db->exec($sql_tag);
        try {
            $stmt = $this->db->prepare($sql);
            $stmt->execute($arr);
            return array('status'=>'ok', 'id'=>$this->db->lastInsertId());
        }  catch (\PDOException $e) {
            return array('status'=>'fail', 'msg'=>$e->getMessage());
        }

    }

    /**
     * 获取座位，返回数组,若总座位数与剩余座位相等则只有total和left，array('total'=>总座位,
     *                         'left'=>剩余座位,
     *                          0=>关闭,1=>预留,2=>锁定,3=>已售出,4=>已退)
     *
     * @param $round_id
     * @return array
     */
    public function CountSeat($round_id)
    {
        $seat_count = array();
        $sql = <<<SQL
    SELECT COUNT(s.*) FROM pft_roundseat s LEFT JOIN pft_round r
    ON r.zone_id=s.zone_id
    WHERE r.id={$round_id} AND s.seat_status=0
SQL;
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $total_seat = $left_seat = $stmt->fetchColumn(0);

        //0关闭1预留2锁定3已售出4已退5不可售
        $sql_seat = <<<SQL
      SELECT COUNT(*) as cnt, `status` FROM pft_roundseat_dyn
      WHERE round_id=$round_id
SQL;
        $this->db->prepare($sql_seat);
        $stmt->execute();
        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            $seat_count[$row['status']] = $row['cnt'];
            if ($row['status']!=4) {
                $left_seat = $total_seat-$row['cnt'];
            }
        }
        $seat_count['total'] = $total_seat;
        $seat_count['left']  = $left_seat;
        return $seat_count;
    }

    /**
     * 添加座位
     *
     * @param int $zone_id 分区ID
     * @return array
     */
    public function CreateRoundSeat($zone_id)
    {
        $data = json_decode($_POST['data'], true);
        if (!count($data)) {
            return array('status'=>'fail', 'msg'=>'数据为空');
        }
        $vals = '';
        foreach ($data as $seat) {
            $vals .= "({$zone_id}, '{$seat['code']}', {$seat['col']},{$seat['row']},{$seat['status']}),";
        }
        $vals = rtrim($vals, ',');
        $sql = "INSERT INTO pft_roundseat(zone_id,seat_code,col_num,row_num,seat_status) VALUES $vals";
        try {
            $this->db->exec($sql);
            return array('status'=>'ok');
        } catch(\PDOException $e) {
            return array('status'=>'fail', 'msg'=> $this->db->errorInfo());
        }
    }

    /**
     * 更新座位状态
     *
     * @param int $seat_id 座位ID
     * @param $status
     * @return array
     */
    public function UpdateRoundSeat($seat_id, $status)
    {
        $sql = "UPDATE pft_roundseat SET status=? WHERE id=? LIMIT 1";
        $stmt = $this->db->prepare($sql);
        if ($stmt->execute(array($seat_id, $status))!==false) {
            return array('status'=>'ok');
        }
        return array('status'=>'fail','msg'=>'更新失败');
    }

    /**
     * 获取产次列表
     *
     * @param int $lid 景区表id
     * @param int $zone_id 分区ID
     * @param null $date
     * @return array
     */
    public function GetRoundList($lid, $zone_id, $date=null)
    {
        $date = is_null($date) ? date('Y-m-d') : $date;
        $sql = "SELECT id,round_name,bt,et FROM pft_round "
            ."WHERE venus_id=? AND use_date=? AND status=1";
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array( $zone_id, $date));
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function RoundDate($venus_id)
    {
        $sql = "SELECT  UNIX_TIMESTAMP(use_date) FROM pft_round WHERE venus_id=? AND status=?";
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($venus_id, 0));
        return $stmt->fetchAll(\PDO::FETCH_COLUMN);
    }

    /**
     * 根据日期获取供应商的所有场次
     *
     * @param Array $params
     * @return array
     */
    public function GetRoundListByDate(Array $params, $need_seat_cnt=false)
    {
        $where = '1=1';
        $search = array();
        array_walk($params, function($val, $key) use (&$where, &$search) {
            $where      .= " AND $key=?";
            $search[]    = $val;
        });

        $sql = <<<SQL
      SELECT r.*,v.venue_name FROM pft_round r
      LEFT JOIN pft_venues v ON v.id=r.venus_id
      WHERE $where
SQL;
        $stmt = $this->db->prepare($sql);
        $stmt->execute($search);
        if ($need_seat_cnt) {
            $lists = array();
            //获取总座位 -- AND seat_status=0  AND seat_status IN(0,5)
            $sql_total_seat = <<<SQL
SELECT count(*) FROM pft_roundseat WHERE venue_id={$params['venus_id']} AND seat_status=0
SQL;
            $stmt_seat = $this->db->prepare($sql_total_seat);
            $stmt_seat->execute();
            $total_seat = $stmt_seat->fetchColumn(0);

            while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                $lists[$row['id']]                = $row;
                $lists[$row['id']]['seat_total']  = $total_seat;
                $lists[$row['id']]['seat_left']   = $total_seat;
            }
            if ($_GET['debug']) {
//                print_r($lists);
            }
            if (!count($lists)) {
                return array();
            }

            $round_id_str = implode(',', array_keys($lists));
            //已占用的座位
            $sql_seat = <<<SQL
SELECT count(*) as cnt,d.round_id,d.`status`,s.seat_status FROM pft_roundseat_dyn d
LEFT JOIN pft_roundseat s ON s.id = d.seat_id WHERE d.round_id IN($round_id_str)
 AND `status`>0 group by d.round_id,d.`status`,s.seat_status
SQL;
//            echo $sql_seat;
            $stmt_seat = $this->db->prepare($sql_seat);
            $stmt_seat->execute();
//            $tmp_total_seat = array_combine(array_keys($lists), array_pad(array(), count($lists), $total_seat));
            while($s = $stmt_seat->fetch(\PDO::FETCH_ASSOC)) {
                if (!$s['cnt']) continue;
//
//                if ($s['status']==5) {
//                    $lists[$s['round_id']]['seat_total'] -= $s['cnt'];
////                    $lists[$s['round_id']]['seat_left']  -= $s['cnt'];
//                }
                if ($s['status']==3 || $s['status']==2 || $s['status']==0 ||$s['status']==1 || $s['status']==5) {
                    $lists[$s['round_id']]['seat_left']  -= $s['cnt'];
                }
//                if ($s['status']==4 && $s['seat_status']!=0) {
//                    $tmp_total_seat[$s['round_id']] += $s['cnt'];
//                }
//                else {
//                    $tmp_total_seat[$s['round_id']] -= $s['cnt'];
//                }
//                $lists[$s['round_id']]['seat_left'] = $tmp_total_seat[$s['round_id']];
            }
            if ($_GET['debug']) {
//                print_r($lists);
            }
            return $lists;
        }
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
    /**
     * 根据会员ID获取场馆列表
     *
     * @param int $apply_did
     * @param int $status
     * @return array
     */
    public function GetVenuesName($apply_did, $status=0)
    {
        $sql = "SELECT id,venue_name,venue_thumb FROM pft_venues WHERE apply_did=? AND status=?";
        $stmt= $this->db->prepare($sql);
        $stmt->execute(array($apply_did, $status));
        $venues = array();
        while($row=$stmt->fetch(\PDO::FETCH_ASSOC)) {
            $venues[] = $row;
        }
        return $venues;
    }

    /**
     * 更新场馆状态
     *
     * @param $venue_id
     * @param $status 0:正常 1：关闭
     * @return array
     */
    public function UpdateVenues($venue_id, $status)
    {
        $sql = "UPDATE pft_venues SET status=$status WHERE id=$venue_id LIMIT 1";
        if ($this->db->exec($sql)!==false) {
            return array('status'=>'ok','msg'=>'更新成功');
        }
        return array('status'=>'fail','msg'=>'更新失败');
    }

    /**
     * 根据场馆ID获取分区
     *
     * @param array $params 查询条件 array(key=>$val)
     * @return array
     * @throws \ErrorException
     */
    public function GetRoundZone(Array $params)
    {
        if (empty($params)) throw new \ErrorException('查询参数不能为空');
        $where = '1=1';
        $search = array();
        array_walk($params, function($val, $key) use (&$where, &$search) {
            $where      .= " AND $key=?";
            $search[]    = $val;
        });
        $sql = "SELECT id,zone_name,total_seats FROM pft_roundzone WHERE $where";
        $stmt= $this->db->prepare($sql);
        $stmt->execute($search);
        $zones = array();
        while($row=$stmt->fetch(\PDO::FETCH_ASSOC)) {
            $zones[] = $row;
        }
        return $zones;
    }


    const SEAT_CLOSE    = 0;//座位关闭
    const SEAT_RESERVE  = 1;//座位预留
    const SEAT_LOCK     = 2;//座位锁定
    const SEAT_SALE     = 3;//座位出售
    const SEAT_BACK     = 4;//座位退票
    const SEAT_FORBID   = 5;//座位禁售

    /**
     * 座位出售
     *
     * @param int $round_id 场次ID
     * @param int $seat_cnt 座位数
     * @param int $order_num 订单号
     * @param int $zone_id 分区ID
     * @return array
     * @throws \ErrorException
     */
    public function SaleSeat($round_id, $seat_cnt,$order_num,$zone_id)
    {
        if (!$round_id) throw new \ErrorException('场馆ID不能为空');
        if (!$zone_id) throw new \ErrorException('分区ID不能为空');
        if (!$order_num) throw new \ErrorException('订单号不能为空');

        $seats = $this->CountSeat($round_id);
        if ($seats['left']<$seat_cnt) {
            throw new \ErrorException('剩余座位不足');
        }

        $sql_get_seat_id = <<<SQL
SELECT id FROM pft_roundseat s WHERE s.zone_id =? AND s.id NOT IN (
SELECT seat_id FROM pft_roundseat_dyn WHERE round_id =?) LIMIT $seat_cnt
SQL;
        $stmt_seat = $this->db->prepare($sql_get_seat_id);
        $stmt_seat->execute(array($zone_id, $round_id));
        $seat_id_list = $stmt_seat->fetchAll(\PDO::FETCH_COLUMN);
        if (count($seat_id_list)<$seat_cnt) {
            throw new \ErrorException('剩余座位不足');
        }
        $vals  = '';
        for($i=0;$i<$seat_cnt;$i++) {

            $vals .= "($seat_id_list[$i], $round_id,$order_num,".self::SEAT_SALE."),";
        }
        $vals = rtrim($vals, ',');
        $sql_sale = <<<SQL
INSERT INTO pft_roundseat_dyn(seat_id,round_id,ordernum,status)
 VALUES $vals
SQL;
        if ($this->db->exec($sql_sale)!==false) {
            return array('status'=>'ok');
        }
        return array('status'=>'fail', 'msg'=>$this->db->errorInfo());
    }

    public function DynSeatGetOld_20151009($round_id)
    {
        if ($_SESSION['account']==123624) {
            return $this->DynSeatGetBeta($round_id);
        }
        $sql_chk = "SELECT venus_id FROM pft_round WHERE id=? LIMIT 1";
        $stmt = $this->db->prepare($sql_chk);
        $stmt->execute(array($round_id));
        if ($venus_id = $stmt->fetchColumn(0)) {
            $sql    = "SELECT seat_id,status FROM pft_roundseat_dyn WHERE round_id=?";
            $stmt   = $this->db->prepare($sql);
            $stmt->execute(array($round_id));
            $list   = $stmt->fetchAll(\PDO::FETCH_ASSOC);

            $sql_total_seat = <<<SQL
SELECT count(*) as cnt,zone_id FROM pft_roundseat WHERE venue_id={$venus_id}
AND seat_status=0 group by zone_id
SQL;
            $stmt_seat = $this->db->prepare($sql_total_seat);
            $stmt_seat->execute(array($round_id));
            while($tmp=$stmt_seat->fetch(\PDO::FETCH_ASSOC)) {
                $total_seat[$tmp['zone_id']]['total'] = $tmp['cnt'];
                $total_seat[$tmp['zone_id']]['left']  = $tmp['cnt'];
            }
            $sql_seat = <<<SQL
SELECT count(*) as cnt,d.`status`,d.zone_id,s.seat_status FROM pft_roundseat_dyn d
 LEFT JOIN pft_roundseat s ON s.id=d.seat_id WHERE d.round_id=$round_id
AND `status`>0 group by d.`status`,d.zone_id
SQL;
//            echo $sql_seat;
            $stmt_seat = $this->db->prepare($sql_seat);
            $stmt_seat->execute();
            while($s = $stmt_seat->fetch(\PDO::FETCH_ASSOC)) {
                if (!$s['cnt']) {
                    continue;
                }
                if ($s['seat_status']!=0 && $s['status']==4) {
                    $total_seat[$s['zone_id']]['total'] += $s['cnt'];
                    $total_seat[$s['zone_id']]['left']  += $s['cnt'];
                }
                elseif ($s['status']==5 ) {
                    $total_seat[$s['zone_id']]['total'] -= $s['cnt'];
                    $total_seat[$s['zone_id']]['left']  -= $s['cnt'];
                }
                else{
                    //if ($s['status']==0 || $s['status']==1 || $s['status']==2 || $s['status']==3 )
                    $total_seat[$s['zone_id']]['left']  -= $s['cnt'];
                }
            }
//            print_r($total_seat);
//            if ($_GET['debug']) {
//                print_r($total_seat);
//            }
            return array(
                'status'=>'ok',
                'list'  => $list,
                'zones' => $total_seat,
            );
        }
        return array(
            'status'=> 'fail',
            'msg'   => '场次不存在'
        );
    }
    public function DynSeatGet($round_id)
    {
        $sql_chk = "SELECT venus_id FROM pft_round WHERE id=? LIMIT 1";
        $stmt = $this->db->prepare($sql_chk);
        $stmt->execute(array($round_id));
        if ($venus_id = $stmt->fetchColumn(0)) {
            $sql    = "SELECT seat_id,status FROM pft_roundseat_dyn WHERE round_id=?";
            $stmt   = $this->db->prepare($sql);
            $stmt->execute(array($round_id));
            $list   = $stmt->fetchAll(\PDO::FETCH_ASSOC);

            $sql_total_seat = <<<SQL
select id,seat_status,zone_id from pft_roundseat
where venue_id={$venus_id} ORDER BY zone_id asc
SQL;
            $stmt_seat = $this->db->prepare($sql_total_seat);
            $stmt_seat->execute(array($round_id));
            $total_seat = $seat_data = $left_seat = array();
            while($tmp=$stmt_seat->fetch(\PDO::FETCH_ASSOC)) {
                $seat_data[$tmp['id']] = $tmp;
                if ($tmp['seat_status']==0) {
                    $total_seat[$tmp['zone_id']]['total'] += 1;
                    $total_seat[$tmp['zone_id']]['left'] = $total_seat[$tmp['zone_id']]['total'];
                }
            }
            $sql_seat = <<<SQL
SELECT d.seat_id,d.zone_id,d.status FROM pft_roundseat_dyn d WHERE d.round_id=$round_id
SQL;
//            echo $sql_seat;
            $stmt_seat = $this->db->prepare($sql_seat);
            $stmt_seat->execute();
            while($s = $stmt_seat->fetch(\PDO::FETCH_ASSOC)) {
                if ($s['status']==4 ) {
                    if ($seat_data[$s['seat_id']]['seat_status']!=0) {
                        //若场馆座位不可售，场次座位设置成可售，那么总库存增加
                        $total_seat[$s['zone_id']]['total'] += 1;
                        $total_seat[$s['zone_id']]['left']  += 1;
                    }
                } elseif ($s['status']==5) {
                    //场次座位不可售，场馆座位可售，那么总库存应该减少
                    if ($seat_data[$s['seat_id']]['seat_status']!=5) {
                        $total_seat[$s['zone_id']]['total'] -= 1;
                        $total_seat[$s['zone_id']]['left']  -= 1;
                    }
//                    continue;
                } else {
                    //锁定，出售，预留等皆视为库存减少
                    $total_seat[$s['zone_id']]['left']  -= 1;
                }
            }
//            print_r($total_seat);
//            if ($_GET['debug']) {
//                print_r($total_seat);
//            }
//            foreach ($total_seat as $zone_id=>$_cnt) {
//                $total_seat[$zone_id]['total'] = $_cnt;
//            }
            return array(
                'status'=>'ok',
                'list'  => $list,
                'zones' => $total_seat,
            );
        }
        return array(
            'status'=> 'fail',
            'msg'   => '场次不存在'
        );
    }

    /**
     * 场次座位关闭预留锁定及释放
     *
     * @param int $round_id  场次ID
     * @param int $order_num 订单号
     * @param int $seat_id 座位ID
     * @param int $seat_state 0关闭1预留2锁定3已售出4已退
     * @return bool|int
     * @throws \ErrorException
     */
    public function DynSeatSet($round_id, $order_num, $seat_id=0, $seat_state=0,$zone_id=0)
    {
        $ret = false;
        //检测该场次该座位是否已经被占
        $sql = <<<SQL
    SELECT id,seat_id,status,ordernum FROM pft_roundseat_dyn
    WHERE seat_id=? AND round_id=? LIMIT 1
SQL;
        $stmt= $this->db->prepare($sql);
        $stmt->execute(array($seat_id, $round_id));
        $data = $stmt->fetch(\PDO::FETCH_ASSOC);
//        print_r($data);
        switch ($seat_state) {
            case self::SEAT_CLOSE:
            case self::SEAT_RESERVE:
            case self::SEAT_LOCK:
            case self::SEAT_FORBID:
                //已经被占用
                if ($data) {
                    if ($data['status']==$seat_state) {
                        throw new \ErrorException('该场次该座位已经设定');
                    }
                    elseif ($data['status']==self::SEAT_SALE) {
                        throw new \ErrorException('该场次该座位已经出售');
                    }
                    elseif ($data['status']==self::SEAT_LOCK) {
                        throw new \ErrorException('该场次该座位已经锁定');
                    }
                    $sql = <<<SQL
    UPDATE pft_roundseat_dyn SET status={$seat_state}
    WHERE id={$data['id']} LIMIT 1
SQL;
                }
                else {
                    $sql = <<<SQL
    INSERT INTO pft_roundseat_dyn SET seat_id={$seat_id},round_id={$round_id},
    ordernum=0,status={$seat_state},zone_id=$zone_id,
    opid='{$_SESSION['memberID']}',create_time={$_SERVER['REQUEST_TIME']}
SQL;
                }
//                echo $sql . PHP_EOL;
                $ret = $this->db->exec($sql);
                break;
            //取消订单，释放座位
            case self::SEAT_BACK:
                if ($data) {
                    if ($data['ordernum']>100000) {
                        throw new \ErrorException('抱歉，该订单已经被占，无法取消');
                    }
                    if ($seat_id && $round_id) {
                        $sql = 'SELECT id FROM pft_roundseat_dyn WHERE seat_id=? AND round_id=? LIMIT 1';
                        $param_arr = array($seat_id, $round_id);
                    }
                    else {
                        $sql = 'SELECT id FROM pft_roundseat_dyn WHERE ordernum=? AND status=?';
                        $param_arr = array($order_num, self::SEAT_SALE);
                    }
                    $stmt= $this->db->prepare($sql);
                    $stmt->execute($param_arr);
                    $data = $stmt->fetchAll(\PDO::FETCH_COLUMN);
                    if (!$data) {
                        throw new \ErrorException('抱歉，该订单座位信息不存在');
                    }
                    $update_id_list = implode(',', $data);
                    $sql_update = "UPDATE pft_roundseat_dyn SET status=".self::SEAT_BACK
                        . " WHERE id IN($update_id_list) LIMIT " . count($data);
                }
                else {
                    $sql_update = <<<SQL
    INSERT INTO pft_roundseat_dyn SET seat_id={$seat_id},round_id={$round_id},
    ordernum=0,status={$seat_state},zone_id=$zone_id,
    opid='{$_SESSION['memberID']}',create_time={$_SERVER['REQUEST_TIME']}
SQL;
                }
//                echo $sql_update;
                $ret = $this->db->exec($sql_update);
                break;
        }
        return $ret;
    }

} #EOF CLASS